<?php
class Setting {
    private $conn;
    private $auth;

    public function __construct(PDO $conn, Auth $auth) {
        $this->conn = $conn;
        $this->auth = $auth;
    }

    /**
     * 获取所有配置项
     * @route GET /settings/getAll
     * 返回格式：['app_home_banner' => 'path1.jpg', 'app_profile_banner' => 'path2.png']
     */
    public function getAll(): void {
        try {

            $stmt = $this->conn->query("SELECT `id`, `type`, `url` FROM settings");
            $settings = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // 按 type 分组
            $grouped = [];
            foreach ($settings as $item) {
                $type = $item['type'];
                $grouped[$type][] = [
                    'id' => $item['id'],
                    'url' => $item['url']
                ];
            }

            echo json_encode([
                'code' => 200,
                'data' => $grouped
            ]);

        } catch (Exception $e) {
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'msg' => $e->getMessage(),
                'data' => null
            ]);
        }
    }

    /**
     * 更新某个配置项
     * @route POST /settings/update
     * 传入参数（JSON 格式）：
     * {
     *   "id": 1,
     *   "type": "app_home_banner",
     *   "url": "/api/attachment/2024-08/banner123.jpg"
     * }
     */
    public function update(): void {
        try {
            $this->auth->checkAdmin(); // 只允许管理员修改

            $data = json_decode(file_get_contents('php://input'), true);

            // 获取参数
            $id = $data['id'] ?? null;
            $type = $data['type'] ?? '';
            $url = $data['url'] ?? '';

            // 验证必要参数
            if (empty($id)) {
                throw new Exception("配置项的 id 不能为空", 400);
            }
            if (empty($type)) {
                throw new Exception("配置项的 type 不能为空", 400);
            }
            if (empty($url)) {
                throw new Exception("配置项的 url 不能为空", 400);
            }

            // 使用预处理语句防止SQL注入，并根据ID更新记录
            $stmt = $this->conn->prepare("
                UPDATE settings 
                SET `type` = :type, `url` = :url 
                WHERE `id` = :id
            ");

            // 绑定参数并执行
            if (!$stmt->execute([
                ':type' => $type,
                ':url' => $url,
                ':id' => $id
            ])) {
                throw new Exception("保存配置失败", 500);
            }

            // 检查是否确实更新了记录
            if ($stmt->rowCount() === 0) {
                echo json_encode([
                    'code' => 404,
                    'msg' => "未找到ID为 {$id} 的配置项，更新未执行",
                    'data' => null
                ]);
                return;
            }

            echo json_encode([
                'code' => 200,
                'msg' => '配置更新成功',
                'data' => [
                    'id' => $id,
                    'type' => $type,
                    'url' => $url
                ]
            ]);

        } catch (Exception $e) {
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'msg' => $e->getMessage(),
                'data' => null
            ]);
        }
    }

    /**
     * 新增配置项
     * @route POST /settings/add
     * 传入参数（JSON 格式）：
     * {
     *   "type": "app_home_banner",
     *   "url": "/api/attachment/2024-08/new_banner.jpg"
     * }
     */
    public function add(): void {
        try {
            $this->auth->checkAdmin(); // 只允许管理员添加

            $data = json_decode(file_get_contents('php://input'), true);

            // 获取参数
            $type = $data['type'] ?? '';
            $url = $data['url'] ?? '';

            // 验证必要参数
            if (empty($type)) {
                throw new Exception("配置项的 type 不能为空", 400);
            }
            if (empty($url)) {
                throw new Exception("配置项的 url 不能为空", 400);
            }

            // 使用预处理语句防止SQL注入
            $stmt = $this->conn->prepare("
                INSERT INTO settings (`type`, `url`, `created_at`) 
                VALUES (:type, :url, NOW())
            ");

            // 绑定参数并执行
            if (!$stmt->execute([
                ':type' => $type,
                ':url' => $url
            ])) {
                throw new Exception("添加配置失败", 500);
            }

            // 获取新插入的ID
            $newId = $this->conn->lastInsertId();

            echo json_encode([
                'code' => 200,
                'msg' => '配置添加成功',
                'data' => [
                    'id' => $newId,
                    'type' => $type,
                    'url' => $url
                ]
            ]);

        } catch (Exception $e) {
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'msg' => $e->getMessage(),
                'data' => null
            ]);
        }
    }

    /**
     * 删除配置项
     * @route POST /settings/delete
     * 传入参数（JSON 格式）：
     * {
     *   "id": 1
     * }
     */
    public function delete(): void {
        try {
            $this->auth->checkAdmin(); // 只允许管理员删除

            $data = json_decode(file_get_contents('php://input'), true);

            // 获取参数
            $id = $data['id'] ?? null;

            // 验证必要参数
            if (empty($id)) {
                throw new Exception("配置项的 id 不能为空", 400);
            }

            // 使用预处理语句防止SQL注入
            $stmt = $this->conn->prepare("
                DELETE FROM settings 
                WHERE `id` = :id
            ");

            // 绑定参数并执行
            if (!$stmt->execute([':id' => $id])) {
                throw new Exception("删除配置失败", 500);
            }

            // 检查是否确实删除了记录
            if ($stmt->rowCount() === 0) {
                echo json_encode([
                    'code' => 404,
                    'msg' => "未找到ID为 {$id} 的配置项，删除未执行",
                    'data' => null
                ]);
                return;
            }

            echo json_encode([
                'code' => 200,
                'msg' => '配置删除成功',
                'data' => [
                    'id' => $id
                ]
            ]);

        } catch (Exception $e) {
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'msg' => $e->getMessage(),
                'data' => null
            ]);
        }
    }
}